import java.util.HashMap;
import java.util.Map;

/**
 * @program: LeetCode
 * @description: LeetCode : 剑指 Offer II 010. 和为 k 的子数组
 * @author: WXY
 * @create: 2022-12-21 14:36
 * @Version 1.0
 **/

public class offer_four1_subarraySum {
    public static int subarraySum(int[] arr, int k) {
        int len = arr.length;
        int pre = 0;
        int ans = 0;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(pre, 1);
        for (int i = 0; i < len; i++) {
            pre += arr[i];
            if (map.containsKey(pre - k)) {
                ans += map.get(pre - k);
            }
            map.put(pre, map.getOrDefault(pre, 0) + 1);
        }
        return ans;
    }
}
